package com.qf.service.impl;

import com.qf.mapper.MemberMapper;
import com.qf.service.BusinessService;
import com.qf.utils.ThreadPoolUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

@Service
public class BusinessServiceImpl implements BusinessService {

    //注入会员相关信息的mapper
    @Autowired
    private MemberMapper memberMapper;

    //注入订单相关信息的mapper

    @Override
    public Map<String, Object> getData() throws InterruptedException {

        Map<String,Object> data = new HashMap<>();

        //并发包下的门闩对象 AQS
        CountDownLatch cdl = new CountDownLatch(4);

        ThreadPoolUtils.threadPoolExecutor().submit(()->{
            try {
                long todayNewMember = memberMapper.todayNewMember(); //2s
                data.put("todayNewMember", todayNewMember);
            }finally {
                //减少门闩数量
                cdl.countDown();
            }
        });
        ThreadPoolUtils.threadPoolExecutor().submit(()->{
            try {
                long weekNewMember = memberMapper.weekNewMember(); //2s
                data.put("thisWeekNewMember", weekNewMember);
            }finally {
                //减少门闩数量
                cdl.countDown();
            }

        });
        ThreadPoolUtils.threadPoolExecutor().submit(()->{
            try{
                long monthNewMember = memberMapper.monthNewMember(); //3s
                data.put("thisMonthNewMember",monthNewMember);
            }finally {
                //减少门闩数量
                cdl.countDown();
            }

        });
        ThreadPoolUtils.threadPoolExecutor().submit(()->{
            try {
                long memberCount = memberMapper.memberCount(); //1s
                data.put("totalMember",memberCount);
            }finally {
                //减少门闩数量
                cdl.countDown();
            }
        });


        //等待门闩数量减为0，继续向下执行
        cdl.await();

        return data;

        // 开启n个线程，每个线程内部随机休眠一段时间，求所有线程执行完成的最短时间
    }
}
